import datetime
import os
import random

import time
import uuid

from common.extend import ImageCode
from flask import render_template, request, redirect, url_for, session, jsonify, make_response, g, abort, \
    render_template_string
from application import db, mail, app, red
from flask_mail import Message
from web.forms.user_forms import RegisterForms, LoginForm, QuestionForm
from web.models.boke_models import User, Credit, QuestionModel, Category, Collection
from werkzeug.security import generate_password_hash, check_password_hash
from web.views.user import user_app


@user_app.before_request
def judge_user():
    lst = ['/user/logout', '/user/site', '/user/article_center', '/user/article_edit', '/user/delete_article',
           '/user/set_sm']
    if request.path in lst and not g.user:
        js_alert = "<script>alert('请先登录!');</script>"
        return render_template_string(js_alert)


# 注册
@user_app.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        form = RegisterForms(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user_exist = User.query.filter_by(email=email).first()
            if not user_exist:
                user = User(username=username, password=generate_password_hash(password), email=email, credit=50)

                db.session.add(user)
                db.session.commit()
                # 增加积分记录
                credit = Credit(author_id=user.id, category='注册用户', target=0, all_credit=50)
                db.session.add(credit)
                db.session.commit()

                # 将cookie写入浏览器
                # responses = make_response('login-pass')
                # responses.set_cookie('username',username,max_age=30*24*3600)
                # responses.set_cookie('username',password,max_age=30*24*3600)
                # return responses
                return jsonify({'recode': 1})
            else:
                return jsonify({'recode': 0, 'error': '邮箱已被注册！'})

        else:
            print(form.errors)
            return jsonify(form.errors)


@user_app.route('/vcode')
def vcode():
    code, bstring = ImageCode().get_code()
    response = make_response(bstring)
    response.headers['Content-Type'] = 'image/jpeg'
    session['vcode'] = code.lower()
    print(code)
    return response


# 登录
@user_app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            user = User.query.filter_by(email=form.email.data).first()
            session['user_id'] = user.id
            # 创建响应对象并设置Cookie
            response = jsonify({'code': 1})
            response.set_cookie('user_id', str(user.id))  # 设置名为'user_email'的Cookie
            return response
        else:
            print(form.errors)
            return jsonify(form.errors)


@user_app.route('/logout')
def logout():
    session.clear()
    response = make_response(redirect(url_for('index.bbs')))
    response.delete_cookie('user_id')  # 设置过期时间为过去的时间
    return response


# 用户中心
@user_app.route('/site')
def site():
    # 查询所有评论
    questions = g.user.boke_question

    comments_num = 0
    for i in questions:
        comments_num += int(i.replycount)

    return render_template('user-side.html', comments_num=comments_num)


# 文章中心
@user_app.route('/article_center')
def article_center():
    global sm_lst
    type = request.args.get('type')
    print('类型', type)
    if type == '1':
        questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 1,
                                               QuestionModel.hidden == 0, QuestionModel.author == g.user).order_by(
            QuestionModel.create_time.desc()).all()

        sm_lst = []
        for i in questions:
            if int(i.hidden) == 1:
                sm_lst.append(i)
    elif type == '2':
        questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 0,
                                               QuestionModel.hidden == 0, QuestionModel.author == g.user).order_by(
            QuestionModel.create_time.desc()).all()
        sm_lst = []
        for i in questions:
            if int(i.hidden) == 1:
                sm_lst.append(i)
    elif type == '3':
        questions = QuestionModel.query.filter(QuestionModel.draft == 1, QuestionModel.check == 0,
                                               QuestionModel.hidden == 0, QuestionModel.author == g.user).order_by(
            QuestionModel.create_time.desc()).all()
        sm_lst = []
        for i in questions:
            if int(i.hidden) == 1:
                sm_lst.append(i)
    elif type == '4':
        questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.hidden == 1,
                                               QuestionModel.author == g.user).order_by(
            QuestionModel.create_time.desc()).all()
        sm_lst = []
        for i in questions:
            if int(i.hidden) == 1:
                sm_lst.append(i)
    elif type == '5':
        questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 0,
                                               QuestionModel.hidden == 0).order_by(
            QuestionModel.create_time.desc()).all()
        sm_lst = None
    elif type == '6':
        questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 3,
                                               QuestionModel.hidden == 0, QuestionModel.author == g.user).order_by(
            QuestionModel.create_time.desc()).all()
        sm_lst = []
        for i in questions:
            if int(i.hidden) == 1:
                sm_lst.append(i)

    return render_template('article-all.html', questions=questions, sm_lst=sm_lst, type=type)


# 编辑文章
@user_app.route('/article_edit', methods=['GET', 'POST'])
def article_edit():
    if request.method == 'GET':
        id = request.args.get('article_id')
        category = Category.query.all()
        questions = QuestionModel.query.filter_by(id=id).first()
        return render_template('edit.html', question=questions, category=category)
    else:
        print('当前发布文章')
        global new_filename
        new_filename = '默认.jpg'
        print(request.form)
        if not request.form.get('use_credit').isdigit():
            return jsonify({'credit': '应为数字！'})
        form = QuestionForm(request.form)
        print(form)
        if form.validate():
            f = request.files['files']
            # 保存文件资源
            try:
                if f:
                    filename = str(uuid.uuid4())
                    new_filename = filename + '.' + str(f.filename.split('.')[-1])
                    f.filename = new_filename

                    # 保存文件到指定文件夹
                    file_path = os.path.join(app.config['UPLOAD_FOLDER'], new_filename)
                    f.save(file_path)
            except Exception as e:
                print(e)

            title = request.form.get('title')
            content = request.form.get("content")
            detail = request.form.get("detail")
            credit = request.form.get("use_credit")
            category_id = request.form.get("category")
            hidden = request.form.get("hidden")
            article_id = request.args.get("article_id")

            question = QuestionModel.query.filter_by(id=article_id).first()
            question.title = title
            question.content = content
            question.detail = detail
            question.credit = credit
            question.category_id = category_id
            question.hidden = hidden
            question.article_id = article_id
            question.cover = new_filename
            question.check = 0

            db.session.add(question)
            db.session.commit()
            # todo: 跳转到这篇问答的详情页
            return jsonify({'code': 200})
        else:
            return jsonify(form.errors)


# 删除文章
@user_app.route('/delete_article', methods=['POST'])
def article_delete():
    id = request.args.get('article_id')
    question = QuestionModel.query.filter_by(id=id).first()
    db.session.delete(question)
    db.session.commit()
    return jsonify('ok')


@user_app.route('/set_sm', methods=['POST'])
def set_sm():
    id = request.args.get('article_id')
    question = QuestionModel.query.filter_by(id=id).first()
    if int(question.hidden) == 0:
        question.hidden = 1
    else:
        print('私密')

        question.hidden = 0
    db.session.add(question)
    db.session.commit()

    return jsonify('ok')


# 发送邮件
@user_app.route('/get_email/<email>', methods=['GET', 'POST'])
def get_email(email):
    msg = Message(subject='欢迎注册逐梦资源论坛！', sender=app.config['MAIL_USERNAME'], recipients=[email])
    # 获取验证码
    code = get_code(email)
    msg.html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>逐梦大陆-逐梦资源论坛</title>
    </head>
    <body>
        <h1>注册验证码</h1>
        <p>你好，亲爱的[{email}]，</p>
        <p>你的验证码是：<strong>[你的验证码:{code}]</strong></p>
        <p>请使用此验证码来验证你的邮箱地址。</p>
        <p>请在5分钟之内完成验证。</p>
        <p>如果你没有请求此验证码，请忽略此邮件。</p>
        <p>逐梦资源论坛官方</p>
    </body>
    </html>
    """
    print('当前邮箱验证码: ', code)
    try:
        mail.send(msg)
    except Exception as e:
        print('邮件错误：', e)
        return jsonify({'code': 0})

    return jsonify({'code': 1})


# 获取邮件验证码
def get_code(user):
    code = random.randint(10000, 99999)

    # red.hmset("code", {user: str(code) + '/' + str(time.time())})
    session['code'] = str(code) + '-' + str(time.time())
    return code


# 文章判断
@user_app.route('/judge_article', methods=['GET', 'POST'])
def judge_article():
    if g.user.email == '2480419172@qq.com':
        article_id = request.args.get('article_id')
        type = request.args.get('type')
        question = QuestionModel.query.filter_by(id=article_id).first()

        if type == '1':
            question.check = 1
        else:
            question.check = 3
        db.session.add(question)
        db.session.commit()
        return jsonify('ok')
    else:
        abort(404)


# 收藏文章返回
@user_app.route('/collection')
def collection():
    collection = Collection.query.filter_by(author=g.user, canceled=0).all()
    return render_template('collection.html', questions=collection)


# 修改头像
@user_app.route('/change_photo',methods=['GET','POST'])
def change_photo():
    f = request.files['file']

    filename = str(uuid.uuid4())
    new_filename = filename + str(time.time()) + '.' + str(f.filename.split('.')[-1])
    print(new_filename)
    f.filename = new_filename

    # 保存文件到指定文件夹
    file_path = os.path.join(app.config['PHOTO_FOLDER'], new_filename)
    f.save(file_path)

    user = User.query.filter_by(id=g.user.id).first()
    user.photo = new_filename
    db.session.add(user)
    db.session.commit()
    return jsonify('ok')
